<?php

/**
 * users actions.
 *
 * @package    corpon
 * @subpackage users
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class usersActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->users = new User();

    $filter = "-1";
    if ($this->getUser()->hasCredential('Company')) :
      $filter = $this->getUser()->getAttribute('id_account');
    endif;
    
    $this->pager = new sfDoctrinePager('User',sfConfig::get('app_max_users'));
    $this->pager->setQuery($this->users->getUsersQuery($filter));
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();

    $this->users = $this->pager->getResults();
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->user = Doctrine_Core::getTable('User')->find(array($request->getParameter('id_user')));
    $this->forward404Unless($this->user);

    if ($this->getUser()->hasCredential('Company') && ($this->getUser()->getAttribute('id_account') != $this->user->getIdAccount())) :
       $this->forward('default','secure');
    endif;
  }

  public function executeLogin(sfWebRequest $request)
  {
    $this->email = $this->request->getParameter('email');
    $this->password = md5($this->request->getParameter('password'));
    $this->user = Doctrine_Core::getTable('User')->createQuery('u')
                        ->where('u.email = ?', $this->email)
                        ->andWhere('u.password = ?', $this->password);

    $this->query = $this->user->fetchOne();
    $credential = "";

    if ($this->query) {
      switch ($this->query->getCredential())
      {
	case "1":
            $credential = "Admin";
            break;
	case "2":
            $credential = "Company";
            break;
        case "3":
            $credential = "User";
            break;
	default:
            $this->forward('default', 'wrongData');
            break;
      }
    } else {
      $this->forward('default', 'wrongData');
    }

    $this->getUser()->setAuthenticated(true);
    $this->getUser()->addCredential($credential);
    $this->getUser()->setAttribute('name', $this->query->getName());
    $this->getUser()->setAttribute('id_user',$this->query->getIdUser());
    $this->getUser()->setAttribute('id_account',$this->query->getIdAccount());
    $this->getUser()->setAttribute('login',$this->query->getLogin());

    if ($this->query->getIdAccount()=="") :
        $this->redirect($this->request->getParameter('web'));
    else :
        $account = Doctrine_Core::getTable('Account')->findOneByIdAccount($this->query->getIdAccount());
        $this->redirect('account_index_products',$account);
    endif;
  }

  public function executeLogout(sfWebRequest $request)
  {
    $this->getUser()->setAuthenticated(false);

    $this->getUser()->clearCredentials();

    if ($this->getUser()->hasCredential('User')) $this->getUser()->getAttributeHolder()->removeNamespace('User');

    if ($this->getUser()->hasCredential('Company')) $this->getUser()->getAttributeHolder()->removeNamespace('Company');

    if ($this->getUser()->hasCredential('Admin')) $this->getUser()->getAttributeHolder()->removeNamespace('Admin');

    $this->getUser()->getAttributeHolder()->remove('id_user');
    $this->getUser()->getAttributeHolder()->remove('name');
    $this->getUser()->getAttributeHolder()->remove('login');
    $this->getUser()->getAttributeHolder()->remove('id_account');

    $this->getUser()->shutdown();

    if ($request->getParameter('companyNameUrl')) :
      $account = Doctrine_core::getTable('Account')->findOneByCompanyNameUrl(array($request->getParameter('companyNameUrl')));
      $this->redirect('account_index_products',$account);
    else :
      $this->redirect('@homepage');
    endif;
    
  }
  
  public function executeNew(sfWebRequest $request)
  {
    $this->form = new UserForm();
                    $today = date('Y-m-d');
      $this->products = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('4')
                ->execute();
  }

  public function executeRegister(sfWebRequest $request)
  {
    if ($this->getUser()->isAuthenticated()) :
      $this->redirect('default/secure');
    endif;

    if ($request->getParameter('companyNameUrl')) :
     $account = Doctrine_Core::getTable('Account')->findOneByCompanyNameUrl(array($request->getParameter('companyNameUrl')));
     $this->forward404Unless($account);
    endif;
    
                $today = date('Y-m-d');
      $this->products = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('4')
                ->execute();
      
    
    $this->form = new UserForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new UserForm();

    $this->processForm($request, $this->form);

    if ($request->getParameter('profile') != 1) :
        $this->setTemplate('new');
    else:
        $this->setTemplate('profile');
    
        $today = date('Y-m-d');

        $this->products = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('4')
                ->execute();
    endif;
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($user = Doctrine_Core::getTable('User')->find(array($request->getParameter('id_user'))), sprintf('Object user does not exist (%s).', $request->getParameter('id_user')));

    if ($this->getUser()->hasCredential('Company') && ($this->getUser()->getAttribute('id_account') != $user->getIdAccount())) :
       $this->forward('default','secure');
    endif;

    $this->form = new UserForm($user);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($user = Doctrine_Core::getTable('User')->find(array($request->getParameter('id_user'))), sprintf('Object user does not exist (%s).', $request->getParameter('id_user')));
    $this->form = new UserForm($user);

    $this->processForm($request, $this->form);

    if ($request->getParameter('profile') != 1) :
        $this->setTemplate('edit');
    else:
        $this->setTemplate('profile');
    endif;
  }

  public function executeProfile(sfWebRequest $request)
  {
    $this->forward404Unless($user = Doctrine_Core::getTable('User')->find(array($this->getUser()->getAttribute('id_user'))), sprintf('Object usuario does not exist (%s).', $request->getParameter('id_user')));

    $this->form = new UserForm($user);

    $today = date('Y-m-d');

    $this->products = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('4')
                ->execute();
  }

  public function executePassword()
  {
    if ($this->getUser()->isAuthenticated()) $this->redirect('@homepage');
  }

  public function executeSavePassword(sfWebRequest $request)
  {
    if ($this->getUser()->isAuthenticated()) $this->redirect('@homepage');

    $this->forward404Unless($request->isMethod('post'));

    $this->usuario = new User();

    $clavenueva = $this->usuario->changePassword($request->getParameter('email'));

    if ($clavenueva)
    {
      //Create the Transport
      $transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
  			->setUsername('no-reply@corppon.com')
  			->setPassword('c0rpp0n20011');

      $sub = 'New Password';
      $from = 'CorpPon - Restore Password';

      $mailer = Swift_Mailer::newInstance($transport);

      $message = Swift_Message::newInstance()

        ->setCharset('utf-8')

	//Give the message a subject
	->setSubject($sub)

	//Set the From address with an associative array
	->setFrom(array('no-reply@corppon.com' => $from))

	//Set the To addresses with an associative array
	->setTo(array($request->getParameter('email')))

	//Give it a body
	->setBody('Your new password is: '.$clavenueva.'<br/><br/>
		You can change it in the profile section. <br/> <br/>
		Saludos, <br/> CorpPon <br/> <br/>
		Please do not reply this message', 'text/html');

	//Send the message
	$result = $mailer->send($message);

	$this->forward('default', 'changedPassword');
      } else {
	$this->forward('default', 'noemail');
      }
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($user = Doctrine_Core::getTable('User')->find(array($request->getParameter('id_user'))), sprintf('Object user does not exist (%s).', $request->getParameter('id_user')));
    $user->delete();

    $this->redirect('users/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $user = $form->save();

      if (!($this->getUser()->isAuthenticated()))  $this->redirect('default/registerSuccefully');

      if ($request->getParameter('profile'))
      {
	  $this->getUser()->setAttribute('name', $user->getName());
	  $this->redirect('users/profile');
      }

      $this->redirect('users/index');
    }
  }
}
